{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mkdir(path):\n",
    "    import os\n",
    "    import shutil\n",
    "    path=path.strip()\n",
    "    path=path.rstrip(\"\\\\\")\n",
    "    isExists=os.path.exists(path)\n",
    "    if not isExists:\n",
    "        os.makedirs(path) \n",
    "        return True\n",
    "    else:\n",
    "        filelist=os.listdir(path) \n",
    "        for f in filelist:\n",
    "            filepath = os.path.join( path, f )  \n",
    "            if os.path.isfile(filepath):           \n",
    "                os.remove(filepath)                 \n",
    "                print(str(filepath)+\" removed!\")\n",
    "            elif os.path.isdir(filepath):\n",
    "                shutil.rmtree(filepath,True)        \n",
    "                print(\"dir \"+str(filepath)+\" removed!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import os\n",
    "import tensorflow.keras.backend as K\n",
    "from tensorflow.keras.losses import categorical_crossentropy\n",
    "from tensorflow.keras.optimizers import Adadelta\n",
    "\n",
    "\n",
    "def export_model(model,\n",
    "                 export_model_dir,\n",
    "                 model_version\n",
    "                 ):\n",
    "    \"\"\"\n",
    "    :param export_model_dir: type string, save dir for exported model\n",
    "    :param model_version: type int best\n",
    "    :return:no return\n",
    "    \"\"\"\n",
    "    with tf.get_default_graph().as_default():\n",
    "        # prediction_signature\n",
    "        tensor_info_input = tf.saved_model.utils.build_tensor_info(model.input)\n",
    "        tensor_info_output = tf.saved_model.utils.build_tensor_info(model.output)\n",
    "        print(model.output.shape, '**', tensor_info_output)\n",
    "        print(model.input.shape, '**', tensor_info_input)\n",
    "        prediction_signature = (\n",
    "            tf.saved_model.signature_def_utils.build_signature_def(\n",
    "                inputs={'images': tensor_info_input}, # Tensorflow.TensorInfo\n",
    "                outputs={'result': tensor_info_output},\n",
    "                #method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)\n",
    "                 method_name= \"tensorflow/serving/predict\")\n",
    "               \n",
    "        )\n",
    "        print('step1 => prediction_signature created successfully')\n",
    "        # This method is used to create a directory，\n",
    "        #Delete old files\n",
    "        mkdir(export_model_dir)\n",
    "        # set-up a builder\n",
    "        export_path_base = export_model_dir\n",
    "        export_path = os.path.join(\n",
    "            tf.compat.as_bytes(export_path_base),\n",
    "            tf.compat.as_bytes(str(model_version)))\n",
    "        builder = tf.saved_model.builder.SavedModelBuilder(export_path)\n",
    "        builder.add_meta_graph_and_variables(\n",
    "            # tags:SERVING,TRAINING,EVAL,GPU,TPU\n",
    "            sess=K.get_session(),\n",
    "            tags=[tf.saved_model.tag_constants.SERVING],\n",
    "            signature_def_map={\n",
    "                'predict':\n",
    "                    prediction_signature,\n",
    "                   tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n",
    "              prediction_signature,\n",
    "\n",
    "            },\n",
    "            )\n",
    "        print('step2 => Export path(%s) ready to export trained model' % export_path, '\\n starting to export model...')\n",
    "        #builder.save(as_text=True)\n",
    "        builder.save()\n",
    "        print('Done exporting!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow\\python\\ops\\resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Colocations handled automatically by placer.\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow\\python\\keras\\utils\\losses_utils.py:170: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.cast instead.\n",
      "WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow\\python\\ops\\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.cast instead.\n"
     ]
    }
   ],
   "source": [
    "model = tf.keras.models.load_model('./12308nenghao.h5')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-bb506ceb18e5>:19: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.\n",
      "(?, 3) ** name: \"dense/BiasAdd:0\"\n",
      "dtype: DT_FLOAT\n",
      "tensor_shape {\n",
      "  dim {\n",
      "    size: -1\n",
      "  }\n",
      "  dim {\n",
      "    size: 3\n",
      "  }\n",
      "}\n",
      "\n",
      "(?, 21, 1) ** name: \"lstm_input:0\"\n",
      "dtype: DT_FLOAT\n",
      "tensor_shape {\n",
      "  dim {\n",
      "    size: -1\n",
      "  }\n",
      "  dim {\n",
      "    size: 21\n",
      "  }\n",
      "  dim {\n",
      "    size: 1\n",
      "  }\n",
      "}\n",
      "\n",
      "step1 => prediction_signature created successfully\n",
      "dir C:/tmp/tfserving/pow\\1 removed!\n",
      "INFO:tensorflow:No assets to save.\n",
      "INFO:tensorflow:No assets to write.\n",
      "step2 => Export path(b'C:/tmp/tfserving/pow\\\\1') ready to export trained model \n",
      " starting to export model...\n",
      "INFO:tensorflow:SavedModel written to: C:/tmp/tfserving/pow\\1\\saved_model.pb\n",
      "Done exporting!\n"
     ]
    }
   ],
   "source": [
    "  export_model(\n",
    "        model,\n",
    "        'C:/tmp/tfserving/pow',\n",
    "        1\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
